<script setup lang="ts">
import { PopoverRoot, PopoverTrigger, PopoverPortal, PopoverContent, type PopoverContentEmits } from 'radix-vue'
import { cn } from '@/lib/utils'

interface PopoverProps {
  open?: boolean
  defaultOpen?: boolean
  modal?: boolean
}

interface PopoverContentProps {
  align?: 'start' | 'center' | 'end'
  side?: 'top' | 'right' | 'bottom' | 'left'
  sideOffset?: number
  class?: string
}

defineOptions({
  inheritAttrs: false
})

const props = withDefaults(defineProps<PopoverProps & PopoverContentProps>(), {
  align: 'center',
  side: 'bottom',
  sideOffset: 4
})

const emits = defineEmits<PopoverContentEmits & {
  'update:open': [value: boolean]
}>()

function handleOpenChange(value: boolean) {
  emits('update:open', value)
}
</script>

<template>
  <PopoverRoot :open="open" :default-open="defaultOpen" :modal="modal" @update:open="handleOpenChange">
    <PopoverTrigger as-child>
      <slot name="trigger" />
    </PopoverTrigger>
    <PopoverPortal>
      <PopoverContent
        :side="side"
        :align="align"
        :side-offset="sideOffset"
        :class="cn(
          'z-[9999] w-auto macos-popover outline-none',
          'data-[state=open]:macos-scale-in',
          'data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:duration-200',
          props.class
        )"
        @escape-key-down="emits('escapeKeyDown', $event)"
        @pointer-down-outside="emits('pointerDownOutside', $event)"
        @focus-outside="emits('focusOutside', $event)"
        @interact-outside="emits('interactOutside', $event)"
      >
        <slot />
      </PopoverContent>
    </PopoverPortal>
  </PopoverRoot>
</template>

